<?php

namespace app\api\service;

use app\api\model\AddressBook as AddressBookModel;
use app\api\model\OrderDetail as OrderDetailModel;
use app\api\model\Orders as OrdersModel;
use app\api\model\ShoppingCart as ShoppingCartModel;
use app\common\exception\BusinessException;
use app\common\service\OrderStatus;
use app\common\service\ReminderStatus;

class Orders
{
    /**
     * 生成订单号
     *
     */
    private function genOrderNumber()
    {
        return time() . mt_rand(1000, 9999);
    }
    /**
     * 用户下单
     *
     * @param array $data
     */
    public function submitOrder($data)
    {
        // 异常情况处理（地址簿为空，收货地址为空）
        $addressBook = AddressBookModel::get($data['addressBookId']);
        if (!$addressBook) {
            throw new BusinessException('地址簿为空');
        }

        $userId = $data['userId'];
        $shoppingCartList = ShoppingCartModel::all(['user_id' => $userId]);
        if (!$shoppingCartList) {
            throw new BusinessException('购物车为空');
        }

        //构造订单数据
        $orders = new OrdersModel();
        $orders->address_book_id = $data['addressBookId'];
        $orders->amount = $data['amount'];
        $orders->delivery_status = $data['deliveryStatus'];
        $orders->estimated_delivery_time = $data['estimatedDeliveryTime'];
        $orders->pack_amount = $data['packAmount'];
        $orders->pay_method = $data['payMethod'];
        $orders->remark = $data['remark'];
        $orders->tableware_number = $data['tablewareNumber'];
        $orders->tableware_status = $data['tablewareStatus'];
        $orders->phone = $addressBook->phone;
        $orders->address = $addressBook->detail;
        $orders->consignee = $addressBook->consignee;
        $orders->number = $this->genOrderNumber();
        $orders->user_id = $userId;
        $orders->status = OrderStatus::PENDING_PAYMENT;
        $orders->pay_status = OrderStatus::UN_PAID;
        // 添加订单
        $orders->save();

        $orderDetailList = [];
        //订单明细数据
        foreach ($shoppingCartList as $key => $shoppingCart) {
            $orderDetailList[] = [
                'name' => $shoppingCart->name,
                'image' => $shoppingCart->image,
                'order_id' => $orders->id,
                'dish_id' => $shoppingCart->dish_id,
                'setmeal_id' => $shoppingCart->setmeal_id,
                'dish_flavor' => $shoppingCart->dish_flavor,
                'number' => $shoppingCart->number,
                'amount' => $shoppingCart->amount,
            ];
        }

        // 向订单明细表插入n条数据
        $orderDetail = new OrderDetailModel;
        $orderDetail->saveAll($orderDetailList);

        // 清理购物车中的数据
        ShoppingCartModel::destroy(['user_id' => $userId]);

        // 设置返回数据
        $result = [
            'id' => $orders->id,
            'orderAmount' => $orders->amount,
            'orderNumber' => $orders->number,
            'orderTime' => $orders->order_time,
        ];
        return $result;
    }

    /**
     * 订单支付
     *
     * @param array $data
     */
    public function paymentOrder($data)
    {
        // 获取订单
        $orders = OrdersModel::get(['number' => $data['orderNumber']]);
        if (!$orders) {
            throw new BusinessException("订单不存在");
        }
        if ($orders->user_id != $data['userId']) {
            throw new BusinessException("无权限操作");
        }
        if ($orders->pay_status == OrderStatus::PAID) {
            throw new BusinessException("订单已支付");
        }
        // 预计送达时间 下单时间加上30分钟
        $estimatedDeliveryTime = date('Y-m-d H:i:s', time() + 1800);

        $orders->status = OrderStatus::TO_BE_CONFIRMED;
        $orders->pay_method = $data['payMethod'];
        $orders->pay_status = OrderStatus::PAID;
        $orders->checkout_time = date('Y-m-d H:i:s');
        $orders->estimated_delivery_time = $estimatedDeliveryTime;
        $orders->save();

       // 触发Workerman推送
        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);
        // 推送的数据，包含uid字段，表示是给这个uid推送
        // 2. 构造推送消息（符合前端约定的JSON格式）
        $data = [
            'uid' => 'uid1',
            'type'      => ReminderStatus::ORDER_REMINDER, // 1=来单提醒，2=客户催单
            'orderId'   => $orders->id, // 订单ID
            'content'   => '新订单：' . $orders->number // 消息内容
        ];
        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($data) . "\n");
        // 读取推送结果
        fread($client, 8192);


        return [
            'estimatedDeliveryTime' => $estimatedDeliveryTime
        ];
    }

    /**
     * 显示历史订单
     *
     * @param array $data
     */
    public function showHistoryOrders($data)
    {
        $orders = OrdersModel::all(function ($query) use ($data) {
            if (!empty($data['status'])) $query->where('status', $data['status']);
            $query->where('user_id', $data['userId'])->page($data['page'], $data['pageSize'])->order('order_time', 'desc');
        });
        $result = [];
        $records = [];
        if ($orders) {
            foreach ($orders as $key => $order) {
                $orderDetailList = [];
                $details = $order->details;
                if ($details) {
                    foreach ($details as $key => $detail) {
                        $orderDetailList[] = [
                            'id' => $detail['id'],
                            'name' => $detail['name'],
                            'orderId' => $detail['order_id'],
                            'dishId' => $detail['dish_id'],
                            'setmealId' => $detail['setmeal_id'],
                            'dishFlavor' => $detail['dish_flavor'],
                            'number' => $detail['number'],
                            'amount' => $detail['amount'],
                            'image' => $detail['image'],
                        ];
                    }
                }
                $records[] = [
                    'id' => $order->id,
                    'number' => $order->number,
                    'status' => $order->status,
                    'userId' => $order->user_id,
                    'addressBookId' => $order->address_book_id,
                    'orderTime' => $order->order_time,
                    'checkoutTime' => $order->checkout_time,
                    'payMethod' => $order->pay_method,
                    'payStatus' => $order->pay_status,
                    'amount' => $order->amount,
                    'remark' => $order->remark,
                    'phone' => $order->phone,
                    'address' => $order->address,
                    'consignee' => $order->consignee,
                    'estimatedDeliveryTime' => $order->estimated_delivery_time,
                    'deliveryStatus' => $order->delivery_status,
                    'packAmount' => $order->pack_amount,
                    'tablewareNumber' => $order->tableware_number,
                    'tablewareStatus' => $order->tableware_status,
                    'orderDetailList' => $orderDetailList,
                ];
            }
            $result['total'] = count($records);
            $result['records'] = $records;
        }
        return $result;
    }

    /**
     * 显示订单详情
     *
     * @param array $data 
     */
    public function showOrderDetail($data)
    {
        $orders = OrdersModel::get($data['id']);
        if (!$orders) {
            throw new BusinessException('没有找到订单');
        }
        if ($orders->user_id != $data['userId']) {
            throw new BusinessException('没有权限');
        }
        $result = [];
        $orderDetailList = [];
        $details = $orders->details;
        if ($details) {
            foreach ($details as $key => $detail) {
                $orderDetailList[] = [
                    'amount' => $detail->amount,
                    'dishFlavor' => $detail->dish_flavor,
                    'dishId' => $detail->dish_id,
                    'id' => $detail->id,
                    'image' => $detail->image,
                    'name' => $detail->name,
                    'number' => $detail->number,
                    'orderId' => $detail->order_id,
                    'setmealId' => $detail->setmeal_id,
                ];
            }
        }

        $result['address'] = $orders->address;
        $result['addressBookId'] = $orders->address_book_id;
        $result['amount'] = $orders->amount;
        $result['cancelReason'] = $orders->cancel_reason;
        $result['cancelTime'] = $orders->cancel_time;
        $result['checkoutTime'] = $orders->checkout_time;
        $result['consignee'] = $orders->consignee;
        $result['deliveryStatus'] = $orders->delivery_status;
        $result['deliveryTime'] = $orders->delivery_time;
        $result['estimatedDeliveryTime'] = $orders->estimated_delivery_time;
        $result['id'] = $orders->id;
        $result['number'] = $orders->number;
        $result['orderDetailList'] = $orderDetailList;
        $result['orderTime'] = $orders->order_time;
        $result['packAmount'] = $orders->pack_amount;
        $result['payMethod'] = $orders->pay_method;
        $result['payStatus'] = $orders->pay_status;
        $result['phone'] = $orders->phone;
        $result['rejectionReason'] = $orders->rejection_reason;
        $result['remark'] = $orders->remark;
        $result['status'] = $orders->status;
        $result['tablewareNumber'] = $orders->tableware_number;
        $result['tablewareStatus'] = $orders->tableware_status;
        $result['userId'] = $orders->user_id;

        return $result;
    }

    /**
     * 取消订单
     *
     */
    public function cancelOrder($data)
    {
        $orders = OrdersModel::get($data['id']);
        if (!$orders) {
            throw new BusinessException('没有找到订单');
        }
        if ($orders->user_id != $data['userId']) {
            throw new BusinessException('没有权限');
        }
        $orders->status = OrderStatus::CANCELLED;
        $orders->save();
    }

    /**
     * 再来一单
     *
     */
    public function repetitionOrder($data)
    {
        $order = OrdersModel::get($data['id']);
        if (!$order) {
            throw new BusinessException('没有找到订单');
        }
        if ($order->user_id != $data['userId']) {
            throw new BusinessException('没有权限');
        }
        // 异常情况处理（地址簿为空，收货地址为空）
        $addressBook = AddressBookModel::get($order->address_book_id);
        if (!$addressBook) {
            throw new BusinessException('地址簿为空');
        }

        //构造订单数据
        $orders = new OrdersModel();
        $orders->address_book_id = $order->address_book_id;
        $orders->amount = $order->amount;
        $orders->delivery_status = $order->delivery_status;
        $orders->estimated_delivery_time = $order->estimated_delivery_time;
        $orders->pack_amount = $order->pack_amount;
        $orders->pay_method = $order->pack_amount;
        $orders->remark = $order->pack_amount;
        $orders->tableware_number = $order->pack_amount;
        $orders->tableware_status = $order->pack_amount;
        $orders->phone = $addressBook->phone;
        $orders->address = $addressBook->detail;
        $orders->consignee = $addressBook->consignee;
        $orders->number = time();
        $orders->user_id = $order->user_id;
        $orders->status = OrderStatus::PENDING_PAYMENT;
        $orders->pay_status = OrderStatus::UN_PAID;
        // 添加订单
        $orders->save();

        $orderDetailList = [];
        $orderDetails = $order->details;
        //订单明细数据
        foreach ($orderDetails as $key => $orderDetail) {
            $orderDetailList[] = [
                'name' => $orderDetail->name,
                'image' => $orderDetail->image,
                'order_id' => $orders->id,
                'dish_id' => $orderDetail->dish_id,
                'setmeal_id' => $orderDetail->setmeal_id,
                'dish_flavor' => $orderDetail->dish_flavor,
                'number' => $orderDetail->number,
                'amount' => $orderDetail->amount,
            ];
        }

        // 向订单明细表插入n条数据
        $orderDetail = new OrderDetailModel;
        $orderDetail->saveAll($orderDetailList);
    }
    
     /**
     * 催单
     *
     */
    public function reminderOrder($data)
    {
        $orders = OrdersModel::get($data['id']);
        if (!$orders) {
            throw new BusinessException("订单不存在");
        }
        if ($orders->user_id != $data['userId']) {
            throw new BusinessException("没有权限");
        }
        // 触发Workerman推送
        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);
        // 推送的数据，包含uid字段，表示是给这个uid推送
        // 2. 构造推送消息（符合前端约定的JSON格式）
        $data = [
            'uid' => 'uid1',
            'type'      => ReminderStatus::CUSTOMER_CONFIRMATION, // 1=来单提醒，2=客户催单
            'orderId'   => $orders->id, // 订单ID
            'content'   => '订单号:' . $orders->number // 消息内容
        ];
        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($data) . "\n");
        // 读取推送结果
        return fread($client, 8192);
    }
}
